<!--
 * @Author: zhangjingyu
 * @Date: 2020-11-03 19:58:05
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-01-04 13:45:38
 * @FilePath: \vprisk10.14\src\views\PublicManage\publicManage\curveManagemen\termStructureDefinition.vue
 * @Description: 期限结构定义
-->
<template>
  <!-- 期限结构定义页面 -->
  <div>
    <el-row class="termStructureDefinition container">
      <el-col style="margin-right:10px;" :span="16" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <el-button @click="addFunc">新增</el-button>
            <el-button @click="editFunc">编辑</el-button>
            <el-button @click="delFunc">删除</el-button>
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <!-- <i class="iconfont icon-export" title="导出" slot="reference"></i> -->
              <!-- <i class="iconfont icon-import" title="导入" slot="reference"></i> -->

              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :model="searchForm"
                    ref="searchForm"
                    label-width="60px"
                    label-position="right"
                    size="mini"
                  >
                    <el-form-item label="编码：">
                      <el-input
                        v-model="searchForm.structureCode"
                        style="width:150px"
                        placeholder="请输入编码"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="名称：">
                      <el-input
                        v-model="searchForm.structureName"
                        style="width:150px"
                        placeholder="请输入名称"
                      ></el-input>
                    </el-form-item>
                  </el-form>
                  <div style="text-align:center;padding:10px">
                    <el-button type="primary" size="mini" @click="searchForm.page=1,searchFunc()">
                      查询</el-button
                    >
                    <el-button
                      size="mini"
                      @click="
                        (searchForm.structureCode = ''),
                          (searchForm.structureName = '')
                      "
                      >重置</el-button
                    >
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width:100%"
          @row-click="multipleTableRowClick"
          @selection-change="multipleTableSelectionChange"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="structureCode"
            label="编号 "
            align="center"
            v-if="tablePick[0]"
            show-overflow-tooltip 
          >
          </el-table-column>
          <el-table-column
            prop="structureName"
            label="名称"
            show-overflow-tooltip 
            align="center"
            v-if="tablePick[1]"
          >
          </el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            v-if="tablePick[2]"
            :formatter="r => r.creator || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="createdTm"
            label="创建时间"
            sortable
            v-if="tablePick[3]"
             show-overflow-tooltip 
            :formatter="row => timeFormat(row.createdTm)"
          >
          </el-table-column>
          <el-table-column
            prop="modifier"
            label="修改人"
            v-if="tablePick[4]"
            :formatter="r => r.creator || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            label="修改时间"
            v-if="tablePick[5]"
             show-overflow-tooltip 
            sortable
            :formatter="row => timeFormat(row.modifiedTm)"
          >
          </el-table-column>
        </el-table>
        <pagination
          @size-change="sizeChange"
          @current-change="pageChange"
          @refresh="searchFunc"
          :current-page="searchForm.page"
           :page-size="searchForm.size"
          :total="total"
        ></pagination>
      </el-col>
      <el-col :span="7" class="content-right">
        <!-- <div class="title" style="padding-left:0;margin-left:0">
          <div style="padding:0 0 20px 20px">
            期限结构值
          </div>
          <div style="float:left;padding:0 0 20px 0px">
            <el-button type="normal" @click="addItemFunc">新增</el-button>
            <el-button type="normal" @click="editItemFunc">编辑</el-button>
            <el-button type="normal" @click="delItemFunc">删除</el-button>
          </div>
        </div> -->
        <upper-template noIcon>
          <div slot="buttonArea">
            <el-button type="normal" @click="addItemFunc">新增</el-button>
            <el-button type="normal" @click="editItemFunc">编辑</el-button>
            <el-button type="normal" @click="delItemFunc">删除</el-button>
          </div>
        </upper-template>
        <el-table
          ref="termValueTable"
          :data="termValueTableList"
          class="isRightTable"
          @row-click="termValueRowClick"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column prop="termValue" label="期限 "></el-table-column>
          <el-table-column
            prop="termUnit"
            label="期限单位"
            :formatter="
              row => {
                return row.termUnit == 'Y'
                  ? '年'
                  : row.termUnit == 'M'
                  ? '月'
                  : '日';
              }
            "
          ></el-table-column>
        </el-table>
        <pagination
          @size-change="sizeChangeItem"
          @current-change="pageChangeItem"
          @refresh="searchFuncItem"
          :current-page="searchFormItem.page"
           :page-size="searchFormItem.size"
          :total="totalItem"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 新增/编辑期限结构 -->
    <el-dialog
      v-dialogDrag
      :title="termFormTitle[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="120px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-form-item label="期限结构编号：" prop="structureCode">
          <el-input
            :disabled="saveFlg == 2"
            v-model="saveForm.structureCode"
            maxlength="100"
          ></el-input>
        </el-form-item>
        <el-form-item label="期限结构名称：" prop="structureName">
          <el-input v-model="saveForm.structureName" maxlength="40"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增/编辑期限结构值 -->
    <el-dialog
      v-dialogDrag
      :title="saveItemTitles[saveItemFlg - 1]"
      :visible.sync="isItemVisible"
      width="514px"
    >
      <el-form
        :model="saveItemForm"
        ref="saveItemForm"
        label-width="87px"
        label-position="left"
        :rules="saveFormItemRules"
      >
        <el-form-item label="期限：" prop="termValue">
          <el-input v-model="saveItemForm.termValue" maxlength="40"></el-input>
        </el-form-item>
        <el-form-item label="期限类型：" prop="termUnit">
          <el-select
            v-model="saveItemForm.termUnit"
            placeholder="请选择"
            style="width:100%"
          >
            <el-option value="D" label="日"></el-option>
            <el-option value="M" label="月"></el-option>
            <el-option value="Y" label="年"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveFuncItem">确 定</el-button>
        <el-button @click="isItemVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { publicManage_pub } from "@/api/index";
import moment from "moment";

export default {
  name: "termStructureDefinition",
  data() {
    return {
      addOrEdit: false, // 新增/编辑字典弹窗
      isItemVisible: false, // 新增/编辑字典项弹窗
      saveFlg: 1, // 1:新增，2：编辑，（字典）
      saveItemFlg: 1, // 1:新增，2：编辑 （字典项）
      termFormTitle: ["添加期限结构定义", "编辑期限结构定义"],
      saveItemTitles: ["添加期限定义", "修改期限定义"],
      // 机构树
      orgList: [
        {
          value: "01",
          label: "一级机构",
          children: [{ value: "001", label: "二级机构" }]
        }
      ],
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        structureCode: "",
        structureName: "",
        page: 1,
        size: 15
      },
      total: 100,
      saveForm: {
        structureCode: "",
        structureName: ""
      },
      saveItemForm: {
        termId: "",
        termValue: "",
        termUnit: "",
        structureCode: ""
      },
      saveFormRules: {
        structureCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[0-9a-zA-Z_]{0,40}$/,
            message: "请输入0-40位英文、数字或下划线",
            trigger: "blur"
          },
          { validator: this.structureCodeValid, trigger: "blur" }
        ],
        structureName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa50-9a-zA-Z_]{0,40}$/,
            message: "请输入0-40位汉字、英文、数字或下划线",
            trigger: "blur"
          },
        ]
      },
      saveFormItemRules: {
        termValue: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[0-9]{0,1}[.0-9]{1,9}$/,
            message: "只能输入1-10位整数或小数",
            trigger: "blur"
          }
        ],
        termUnit: [
          { required: true, message: "请选择期限类型", trigger: "blur" },
          { validator: this.termValueValid, trigger: "blur" }
        ]
      },
      checkList: [],
      checkListRight: [],
      // 列隐藏
      textData: [
        { prop: "1", label: "编号" },
        { prop: "2", label: "名称" },
        { prop: "3", label: "创建人  " },
        { prop: "4", label: "创建时间 " },
        { prop: "5", label: "修改人 " },
        { prop: "6", label: "修改时间 " }
      ],
      // 获取table的数据
      tableData: [],
      termValueTableList: [],
      searchFormItem: {
        page: 1,
        size: 15
      },
      totalItem: 1,
      // 口径层级配置表格列配置
      showConfigData: [
        { prop: "caliberCode", label: "口径编码", align: "center" },
        { prop: "caliberName", label: "口径名称" },
        { prop: "caliberProject.caliberProjectName", label: "所属口径方案 " }
      ],
      addTreeForm: {
        name: "",
        code: ""
      }
    };
  },
  created() {
    this.checkListInit();
    this.searchFunc();
    // console.log(this.tableData, "模拟数据");
  },
  computed: {
    tablePick() {
      return this.$tableDataPick(this.checkList, this.textData);
    }
    // tablePick() {
    //   let arr = [],
    //     arr1 = this.textData,
    //     arr2 = this.checkList;
    //   for (let i = 0; i < arr1.length; i++) {
    //     let flg = false;
    //     for (let j = 0; j < arr2.length; j++) {
    //       if (arr1[i].label === arr2[j]) {
    //         flg = true;
    //       }
    //     }
    //     arr.push(flg);
    //   }
    //   return arr;
    // }
  },
  mounted() {
    // this.getList();
  },
  watch: {
     addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
     isItemVisible() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveItemForm) {
        this.$refs.saveItemForm.clearValidate();
      }
    },
  },
  methods: {
    // 处理save表单机构选中事件
    checkFormOrg() {
      let node = this.$refs.saveOrgTree.getCheckedNodes();
      this.$refs.saveOrgTree.dropDownVisible = false; // 隐藏模态框
      if (node.length != 0) {
        this.saveForm.orgName = node[0].label;
        this.saveOrgTip = node[0].label;
      } else {
        this.saveForm.orgName = "";
        this.saveOrgTip = "";
      }
    },
    // id唯一性校验
    structureCodeValid(rule, value, callback) {
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      publicManage_pub
        .termStructDefCheckExists({
          id: value
        })
        .then(res => {
          if (res.success) {
            callback(new Error("编号已存在"));
          } else {
            callback();
          }
        });
    },
    // 校验期值是否已存在
    termValueValid(rule, value, callback) {
      let data = this.saveItemForm;
      publicManage_pub.termStructcmTermCheckExists(data).then(res => {
        if (res.success) {
          callback(new Error("期限值已存在"));
        } else {
          callback();
        }
      });
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    searchFunc() {
      let data = this.searchForm;
      console.log(this.searchForm);
      publicManage_pub.termStructDefQuery(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.total = res.count;
          this.$nextTick(() => {
            this.multipleTableRowClick(this.tableData[0]);
          });
        }
      });
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
      this.$nextTick(() => {
        // 清除校验结果
        this.$refs.saveForm.clearValidate();
      });
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.saveForm = form;
      this.addOrEdit = true;
    },
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveForm
          };
          publicManage_pub.termStructDefSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.addOrEdit = false;
              this.searchFunc();
            }
          });
        }
      });
    },
    async delFunc() {
      let selection = this.$refs.multipleTable.selection;
      let flg = true;

      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.structureCode) };
          publicManage_pub.termStructDefRemove(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    searchFuncItem() {
      let data = {
        ...this.searchFormItem,
        structureCode: this.tableClickRow.structureCode
      };
      publicManage_pub.termStructcmTermDefQuery(data).then(res => {
        if (res.code == 200) {
          this.termValueTableList = res.data;
          this.totalItem = res.count;
        }
      });
    },
    addItemFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1)
        return this.$message.warning("请选择左侧期限结构");
      if (selection.length > 1)
        return this.$message.warning("只能选择一个期限结构");
      this.saveItemFlg = 1;
      for (let k in this.saveItemForm) {
        this.saveItemForm[k] = "";
      }
      this.saveItemForm.termUnit = "D";
      this.saveItemForm.structureCode = this.tableClickRow.structureCode;
      this.isItemVisible = true;
      this.$nextTick(() => {
        // 清除校验结果
        this.$refs.saveItemForm.clearValidate();
      });
    },
    editItemFunc() {
      this.saveItemFlg = 2;
      let selection = this.$refs.termValueTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row, structureCode: this.tableClickRow.structureCode };
      this.saveItemForm = form;
      this.isItemVisible = true;
    },
    saveFuncItem() {
      this.$refs["saveItemForm"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveItemForm
          };
          publicManage_pub.termStructcmTermDefSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.isItemVisible = false;
              this.searchFuncItem();
            }
          });
        }
      });
    },
    delItemFunc() {
      let selection = this.$refs.termValueTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中期限吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.termId) };
          publicManage_pub.termStructcmTermDefDel(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFuncItem();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleNodeClick() {
      let nodes = this.$refs.caliberConfigTree.getCheckedNodes();
      console.log(nodes);
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    getList() {
      // publicManage.query("我的参数").then(res => {
      //   console.log(res);
      // });
    },
    // 点击表格右侧显示
    multipleTableRowClick(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.tableClickRow = row;
      this.searchFormItem.page=1;
      this.searchFuncItem();
    },
    multipleTableSelectionChange() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length > 0) {
        this.tableClickRow = selection[0];
        if (selection.length == 1) {
          this.searchFuncItem();
        }
      } else {
        this.tableClickRow = {};
      }
    },
    // 行点击即选中
    termValueRowClick(row) {
      if (this.$refs.termValueTable) {
        this.$refs.termValueTable.clearSelection();
      }
      this.$refs.termValueTable.toggleRowSelection(row, true);
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "-";
    },
    // 获取层级配置口径树
    getConfigTree(row) {
      this.$refs.configTable.toggleRowSelection(row);
    },
    sizeChange(val) {
      this.searchForm.size = val;
      console.log(`每页 ${val} 条`);
      this.searchFunc();
    },
    pageChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    sizeChangeItem(val) {
      this.searchFormItem.size = val;
      console.log(`每页 ${val} 条`);
      this.searchFuncItem();
    },
    pageChangeItem(val) {
      this.searchFormItem.page = val;
      console.log(`当前页: ${val}`);
      this.searchFuncItem();
    }
  }
};
</script>

<style lang="scss" scoped>
</style>